import { Injectable } from '@angular/core';
import { Observable, zip } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import { OrganizationService } from 'sparrow-permission-lib';
import { FlatNode } from '../domain/flat-node';
import { NzTreeGetChildren } from './nz-tree-get-children';

@Injectable({
  providedIn: 'root'
})
export class NzTreeGetOrgChildrenService implements NzTreeGetChildren{

  constructor(private orgService: OrganizationService) { }
  getChildren(node: FlatNode): Observable<FlatNode[]> {

    console.log(node)
  const orgs$: any = this.orgService
    .getChildren1(node.id, 'ORGANIZATION', { page: 0, size: node.childCount })
    .pipe(
      map((res) => res.content),
      // tap((res) => console.log(res)),
      switchMap((orgs: any) =>
        zip(
          ...orgs.map((org: any) =>
            this.orgService
              .get4(
                org.id.organizationId === undefined
                  ? org.id
                  : org.id.organizationId
              )
              .pipe(
                map((org_: any) => {
                  return {
                    id: org_.id,
                    label: org_.name,
                    level: node.level + 1,
                    expandable: true,
                    type: 'ORG',
                    childCount: 0,
                  };
                }),
                switchMap((orgNode) =>
                  this.orgService
                    .getChildren1(orgNode.id, 'ORGANIZATION', {
                      page: 0,
                      size: 1,
                    })
                    .pipe(
                      map((count) => {
                        orgNode.expandable =
                          count.totalElements! > 0 ? true : false;
                        orgNode.childCount = count.totalElements!;
                        return orgNode;
                      })
                    )
                )
              )
          )
        )
      ),
      tap((result) => console.log('2222======', result))
    );

  return orgs$
  }
}
